package com.tinyideatech.admin.controller.common;

import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.common.json.JSONObject;
import com.tinyideatech.framework.utils.FtpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/file")
@Api("商城文件管理接口")
public class FileController extends BaseController {

    @Value("${attach_path}")
    private String attach_path;

    @Value("${ftp.catalog}")
    private String catalog;

    @Value("${ftp.modTargetDir}")
    private String modTargetDir;


    @ResponseBody
    @PostMapping("/uploadCar")
    @ApiOperation("车模文件上传")
    public ApiResult uploadCar(HttpServletRequest request) throws IOException, NullPointerException {
        MultipartFile file = getFile(request);
        if (file.isEmpty()) {
            return error("file upload fail");
        }
        String fileName = file.getOriginalFilename();
        String md5 = DigestUtils.md5DigestAsHex(file.getBytes());
        FtpUtil.uploadFileToFtp(catalog + "/" + modTargetDir, fileName, file.getInputStream());
        JSONObject result = new JSONObject();
        result.put("name", fileName);
        result.put("md5", md5);
        return success(result);
    }

    @ResponseBody
    @PostMapping("/upload")
    @ApiOperation("二维码图片文件上传")
    public ApiResult upload(HttpServletRequest request) throws IOException {
        MultipartFile file = getFile(request);
        if (file.isEmpty()) {
            return error("file upload fail");
        }
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 获取UUID名称
        String fileName = UUID.randomUUID() + suffixName;
        // 获取上传文件的File对象
        File dest = new File(attach_path + File.separator + fileName);
        // 开始上传
        if (!dest.getParentFile().exists()) {
            dest.setWritable(true, false);
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            return success("/attach/" + fileName);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return ApiResult.warn("file path not found");
    }

    private MultipartFile getFile(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
        if (map != null) {
            Iterator<String> iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String str = iter.next();
                List<MultipartFile> fileList = map.get(str);
                for (MultipartFile multipartFile : fileList) {
                    return multipartFile;
                }
            }
        }
        return null;
    }

}
